﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Threading;
using Library;
using System.Runtime.Remoting;

namespace TCP_Client
{
    public partial class Form1 : Form
    {
        Socket client; 
        string username;
        BoBai bb = new BoBai();
        List<LaBai> l;
        LaBai LabaiRac;
        byte[] buffer;
        int dem = 0;
        PictureBox a;
        public Form1()
        {
            InitializeComponent();
        }
        public Form1(Socket clientSocket, string Name)
            : this()
        {
            client = clientSocket;
            username = Name;
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            CheckForIllegalCrossThreadCalls = false;
            this.Text = string.Format("Game đánh bài Phỏm :{0}", username);

            var msg = new ChatMessage(username, Command.List, string.Empty);
            buffer = msg.TobyteArray();
            client.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, SendCallBack, null);
            
            try
            {
                buffer = new byte[1024];
                client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None,ReceiveCallBack, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void ReceiveCallBack(IAsyncResult AR)
        {
            try
            {
                client.EndReceive(AR);
                ChatMessage msg = new ChatMessage(buffer);

                switch (msg.CmdType)
                {
                    case Command.Login:
                        txtNhanDL.AppendText(msg.Message);
                        break;
                    case Command.Logout:
                        break;
                    case Command.Message:
                        txtNhanDL.AppendText(string.Format("{0}{1}:{2}{3}", "\r\n", msg.UserName, msg.Message, "\r"));
                        break;
                    case Command.List:
                        int index = int.Parse(msg.Message);
                        HienGR(index);
                        //this.Refresh();
                        break;
                    case Command.Start:
                        string[] m = msg.Message.Split('*');
                        l = new List<LaBai>();
                        int count=Phom.KT(l);
                        txtNhanDL.AppendText(string.Format("hien tai ban co {0} phom",count));
                        Array.ForEach(m, p =>
                            {
                                if(p!="")
                                    l.Add(bb.LayTuTen(p.Split(' ')[0], p.Split(' ')[1]));
                            });
                        Chia(l, this.Width / 2 - 120, this.Height - 180);
                        
                        break;
                    case Command.SanSang:
                        btnStart.Enabled = true;
                        //Form1.ActiveForm.Refresh();
                        break;
                    case Command.Luot:
                        break;
                    case Command.CayRac:
                        m = msg.Message.Split('*');
                        l = new List<LaBai>();
                        l.Add(bb.LayTuTen(m[0], m[1]));
                        index=int.Parse(m[2]);
                        switch (index)
	                    {
                            case 2:
                                Chia(l, this.Width / 2 + 120, this.Height - 250);
                                break;
                            case 1:
                                Chia(l, this.Width / 2 + 120, 140);
                                break;
                            case 3:
                                Chia(l, 72, 140);
                                break;
                            case 4:
                                Chia(l, 72, this.Height - 250);
                                break;
                            default:
                                break;
	                    }
                        
                        break;
                    case Command.Boc:
                        m = msg.Message.Split(' ');
                        LaBai lb = bb.LayTuTen(m[0], m[1]);
                        l = new List<LaBai>();
                        l.Add(lb);
                        Chia(l, this.Width / 2 + 120, this.Height - 180);
                        break;
                    case Command.Chot:
                        break;
                    case Command.An:
                        break;
                    case Command.None:
                        break;
                    default:
                        break;
                }
                buffer = new byte[client.ReceiveBufferSize];
                client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None,ReceiveCallBack, null);
            }
            catch (ObjectDisposedException) { }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            ChatMessage msg = new ChatMessage(username, Command.Start, string.Empty);
            var buffer1 = msg.TobyteArray();
            try
            {
                client.BeginSend(buffer1, 0, buffer1.Length, SocketFlags.None,SendCallBack, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void SendCallBack(IAsyncResult AR)
        {
            try
            {
                client.EndSend(AR);
            }
            catch (ObjectDisposedException) { }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void Chia(List<LaBai> list, int x, int y)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke((MethodInvoker)delegate()
                {
                    PictureBox newp;
                    list.ToList().ForEach(p =>
                    {
                        newp = new PictureBox();
                        newp.Click+=new EventHandler(newp_Click);
                        newp.Location = new Point(x, y);
                        newp.Size = new Size(72, 96);
                        newp.Image = p.Hinh;
                        newp.BorderStyle = BorderStyle.FixedSingle;
                        newp.Cursor = Cursors.Hand;
                        newp.Anchor = AnchorStyles.Bottom;
                        x = x + 25;
                        this.Controls.Add(newp);
                    });
                });
            }
        }

        private void btnDanhbai_Click(object sender, EventArgs e)
        {
            a.Location = new Point(a.Location.X+100, a.Location.Y - 70);
            this.Controls.Remove(a);
            dem = 0;
            /// Send la bai rac
            ChatMessage msg = new ChatMessage(username, Command.CayRac, LabaiRac.So+"*"+LabaiRac.Ten);
            var buffer=msg.TobyteArray();
            client.BeginSend(buffer,0,buffer.Length,SocketFlags.None,new AsyncCallback(SendCallBack),null);

            ///Send thong diep nguoi choi da ket thuc luot
            msg = new ChatMessage(username, Command.Luot, string.Empty);
            buffer = msg.TobyteArray();
            client.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(SendCallBack), null);
        }

        private void btnBocBai_Click(object sender, EventArgs e)
        {
            ///Boc 1 la bai
            ChatMessage msg = new ChatMessage(username, Command.Boc, string.Empty);
            var buffer = msg.TobyteArray();
            client.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(SendCallBack), null);
        }
        private void newp_Click(object e,EventArgs avg)
        {
            a = e as PictureBox;
            dem++;
            switch (dem)
            {
                case 1:
                    a.Location = new  Point(a.Location.X, a.Location.Y-50);
                    LabaiRac = bb.list.Single(p => p.Hinh == a.Image);
                    break;
                case 2:
                    a.Location = new Point(a.Location.X, a.Location.Y + 50);
                    LabaiRac = bb.list.Single(p => p.Hinh == a.Image);
                    dem = 0;
                    break;
            }
        }
        private void HienGR(int index)
        {
            switch (index)
            {
                case 2:
                    this.groupBox1.Visible = true;
                    break;
                case 3:
                    groupBox2.Visible = true;
                    break;
                case 4:
                    groupBox3.Visible = true;
                    break;
            }
        }

        private void txtChat_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                SendMessage(txtChat.Text);
                txtNhanDL.AppendText(string.Format("{0}{1}",txtChat.Text,"\r\n"));
                txtChat.ResetText();          
            }
        }
        private void SendMessage(string text)
        {
            ChatMessage msg = new ChatMessage(username, Command.Message, text);
            var buffer = msg.TobyteArray();
            client.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, SendCallBack, null);
        }

        private void btnready_Click(object sender, EventArgs e)
        {
            ChatMessage msg = new ChatMessage(username, Command.SanSang, string.Empty);
            var buffer = msg.TobyteArray();
            client.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, SendCallBack, null);
            btnready.Enabled = false;
        }
    }
}
